package com.zygh.lz.controller;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.zygh.lz.entity.signfile.SignStatistics;
import com.zygh.lz.service.PatrolrecordService;
import com.zygh.lz.service.SignService;
import com.zygh.lz.stapprove.ResultUtil;
import com.zygh.lz.vo.ExcelDto;
import com.zygh.lz.vo.ResultBean;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
public class ExcelController {

    @Autowired
    private PatrolrecordService patrolrecordService;

    @Resource
    private SignService signService;

    @ApiOperation("日常勤务大队统计报表导出")
    @GetMapping("/exportDdExcel")
    public String exportDdExcel(HttpServletResponse response, String battalion) throws Exception {
        // 创建一个数值格式化对象
        java.text.NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 设置只导出有别名的字段
        writer.setOnlyAlias(true);
        List<Map> mapList = patrolrecordService.countZD(battalion);
        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();

        mapList.forEach(map -> {
            Map<String, Object> row1 = new LinkedHashMap<>();
            Integer ddSDnum = Integer.valueOf(map.get("ddSDnum").toString());
            Integer ddYDnum = Integer.valueOf(map.get("ddYDnum").toString());
            row1.put("组织单位", map.get("ddName"));
            row1.put("应有警力", ddYDnum);
            row1.put("在线警力", ddSDnum);
            if (ddSDnum == 0) {
                row1.put("在线率", 0);

            } else {
                row1.put("在线率", numberFormat.format((float) ddSDnum / (float) ddYDnum * 100));
            }
            rows.add(row1);
        });

        String fileName = System.currentTimeMillis() + ".xlsx";
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(3, "大队在线率统计");


        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        writer.setRowHeight(rows.size() + 2, 55);
        writer.setColumnWidth(-1, 18);
        //设置某几行的对齐方式
        CellStyle style = writer.createCellStyle(0, rows.size() + 2);
        // 右对齐
        style.setAlignment(HorizontalAlignment.LEFT);
        // 垂直对齐
        style.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
        //边框线类型
        style.setBorderBottom(BorderStyle.THIN);
        //下边框线颜色
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        ServletOutputStream out = response.getOutputStream();
        // 关闭writer，释放内存
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);

        return fileName;

    }

    @ApiOperation("日常勤务中队队统计报表导出")
    @GetMapping("/exportZDExcel")
    public String exportZdExcel(HttpServletResponse response, String battalion) throws Exception {
        // 创建一个数值格式化对象
        java.text.NumberFormat numberFormat = NumberFormat.getInstance();
        // 设置精确到小数点后2位
        numberFormat.setMaximumFractionDigits(2);
        // 通过工具类创建writer
        ExcelWriter writer = ExcelUtil.getWriter(true);
        // 设置只导出有别名的字段
        writer.setOnlyAlias(true);
        ArrayList<Map<String, Object>> rows = CollUtil.newArrayList();

        List<Map> mapList = patrolrecordService.countZD(battalion);
        for (Map map : mapList) {
            List<Map> zdCount = (List<Map>) map.get("zdCount");
            for (Map map1 : zdCount) {
                Map<String, Object> row1 = new LinkedHashMap<>();
                Integer SDnum = Integer.valueOf(map1.get("SDnum").toString());
                Integer YDnum = Integer.valueOf(map1.get("YDnum").toString());
                row1.put("组织单位", map1.get("name"));
                row1.put("应有警力", YDnum);
                row1.put("在线警力", SDnum);
                if (SDnum == 0) {
                    row1.put("在线率", 0);

                } else {
                    row1.put("在线率", numberFormat.format((float) SDnum / (float) YDnum * 100));
                }
                rows.add(row1);
            }

        }

        String fileName = System.currentTimeMillis() + ".xlsx";
        // 合并单元格后的标题行，使用默认标题样式
        writer.merge(3, battalion+"中队在线率统计");


        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        writer.setRowHeight(rows.size() + 2, 55);
        writer.setColumnWidth(-1, 18);
        //设置某几行的对齐方式
        CellStyle style = writer.createCellStyle(0, rows.size() + 2);
        // 右对齐
        style.setAlignment(HorizontalAlignment.LEFT);
        // 垂直对齐
        style.setVerticalAlignment(org.apache.poi.ss.usermodel.VerticalAlignment.CENTER);
        //边框线类型
        style.setBorderBottom(BorderStyle.THIN);
        //下边框线颜色
        style.setBottomBorderColor(IndexedColors.BLACK.getIndex());
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        response.setHeader("Content-Disposition",
                "attachment;filename=\"" + URLEncoder.encode(fileName, "UTF-8") + "\"");
        ServletOutputStream out = response.getOutputStream();
        // 关闭writer，释放内存
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);

        return fileName;

    }

    @ApiOperation("导出报表前100")
    @PostMapping("/export/top")
    public String exportTop(HttpServletResponse response,@RequestBody ExcelDto excelDto){
        signService.exportTop(response,excelDto);

        return "SUCCESS";
    }

    @ApiOperation("里程前100")
    @GetMapping("/top/mileages")
    public ResultBean topMileages(ExcelDto excelDto){
        List<SignStatistics> mileages = signService.mileages(excelDto,0);
        return ResultUtil.setOK("查询成功",mileages);
    }

    @ApiOperation("时长前100")
    @GetMapping("/top/duration")
    public ResultBean topDuration(ExcelDto excelDto){
        List<SignStatistics> duration = signService.duration(excelDto,0);
        return ResultUtil.setOK("查询成功",duration);
    }
    @ApiOperation("执法量前100")
    @GetMapping("/top/jiechuNum")
    public ResultBean topJiechuNum(ExcelDto excelDto){
        List<SignStatistics> signStatistics = signService.jiechuNum(excelDto,0);
        return ResultUtil.setOK("查询成功",signStatistics);
    }
}
